

class Gallery {
  scenes = [];
  sceneTagMap = {};

  // 刷新
  initFromServer() {
    return fetchAllSeries()
      .then(scenes => {
        this.refresh(scenes);
        return deepClone(scenes);
      });
  }

  /** 
   * @param {Scene[]} scenes
   */
  refresh(scenes) {
    this.scenes = scenes;

    this.sceneTagMap = {};
    scenes.forEach(scene => {
      scene.tags.forEach(tag => {
        if (this.sceneTagMap[tag] == null) {
          this.sceneTagMap[tag] = [ scene ];
        } else {
          this.sceneTagMap[tag].push(scene);
        }
      })
    });
  }

  getScenesByTag(tag) {
    if (tag == null) {
      return deepClone(this.scenes);
    }

    let scenes = this.sceneTagMap[tag];
    return (scenes == null) ? [] : deepClone(scenes);
  }

  getAllTags() {
    let array = [];
    for (let k in this.sceneTagMap) {
      array.push(k);
    }
    return array;
  }
}

class Scene {
  id = 0;
  series = ''; // 所属系列的名称
  scene = ''; // 场景名

  // 下面部分是和场景生成的屏幕相关
  avatar = ''; // 图标的 Path
  width = ''; // 推荐 scene 的宽
  height = ''; // 推荐 scene 的高
  title = ''; // 场景默认显示的名字, 一般可以为中文
  desc = ''; // 备注
  tags = [];
}

// 去掉方法的深拷贝
function deepClone(obj) {
  return JSON.parse(JSON.stringify(obj));
}



/**
 * @return {Promise<Scene[]>} 从后台发来的 allSeries 数据，已经经过加工
 */
function fetchAllSeries() {
  return fetch('/aurora/asset/allSeries')
    .then((res) => res.json())
    .then((_data) => convertSeries(_data.data));
}

function convertSeries(data) {
  /** @type {Scene[]} */
  const scenes = [];

  for (let seriesName in data) {
    let series = data[seriesName];
    for (let idx = 0; idx < series.scenes.length; idx++) {
      const sd = series.scenes[idx];
      const scene = new Scene();
      // 无 index
      scene.series = seriesName;
      scene.scene = sd.name;
      scene.avatar = sd.gallery.avatar;
      scene.width = sd.gallery.width == null ? "" : "".concat(sd.gallery.width);
      scene.height = sd.gallery.height == null ? "" : "".concat(sd.gallery.height);
      scene.title = sd.gallery.title;
      scene.desc = sd.gallery.desc;
      if (sd.gallery.tags != null && sd.gallery.tags.length > 0) {
        scene.tags.push(...sd.gallery.tags);
      }

      scenes.push(scene);
    }
  }

  scenes.forEach(el => {
    if (el.title == null) {
      el.title = '场景: ' + el.series + ' ' + el.scene;
    }

    if (el.avatar == null) {
      el.avatar = '/aurora/gallery/def_scene_avatar.png';
    } else {
      el.avatar = '/aurora-res/' + el.series + '/' + el.avatar;
    }
  });

  return scenes;
}

export {
  Gallery, Scene
};